#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <string.h>

pid_t child1 = 0, child2 = 0;

// 子进程1信号处理函数
void child1_handler(int sig) {
    printf("Child Process 1 is killed by Parent!\n");
    exit(0);
}

// 子进程2信号处理函数
void child2_handler(int sig) {
    printf("Child Process 2 is killed by Parent!\n");
    exit(0);
}

// 父进程信号处理函数
void parent_handler(int sig) {
    kill(child1, SIGINT);
    kill(child2, SIGINT);
}

int main() {
    int fd[2];
    pipe(fd);

    // 创建子进程1
    child1 = fork();
    if (child1 == 0) {
        signal(SIGINT, child1_handler);
        close(fd[0]); // 关闭读端
        int count = 1;
        char msg[100];
        while (1) {
            snprintf(msg, sizeof(msg), "I send message %d times.\n", count++);
            write(fd[1], msg, strlen(msg) + 1);
            sleep(1);
        }
        exit(0);
    }

    // 创建子进程2
    child2 = fork();
    if (child2 == 0) {
        signal(SIGINT, child2_handler);
        close(fd[1]); // 关闭写端
        char buf[100];
        while (1) {
            int n = read(fd[0], buf, sizeof(buf));
            if (n > 0) {
                printf("%s", buf);
                fflush(stdout);
            }
        }
        exit(0);
    }

    // 父进程
    signal(SIGINT, parent_handler);
    close(fd[0]);
    close(fd[1]);
    // 等待两个子进程结束
    waitpid(child1, NULL, 0);
    waitpid(child2, NULL, 0);
    printf("Parent Process is Killed!\n");
    return 0;
}